<template>
  <div class="app-container">
    <el-descriptions
      class="margin-top"
      title=""
      :column="3"
      :size="'mini'"
      border
    >
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          采购计划
        </template>
        {{ this.purchase.name }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-location-outline"></i>
          截止时间
        </template>
        {{ this.purchase.dueTime }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-mobile-phone"></i>
          采购需求
        </template>
          <el-tooltip class="item" effect="dark" :content="this.purchase.needHerb" placement="top-start">
            <span>{{ellipsis(this.purchase.needHerb)}}</span>
          </el-tooltip>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-tickets"></i>
          联系人
        </template>
        {{ this.purchase.contactName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-office-building"></i>
          电话
        </template>
        {{ this.purchase.contactTel }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-office-building"></i>
          发布时间
        </template>
        {{ this.purchase.addTime }}
      </el-descriptions-item>
    </el-descriptions>

    <el-tabs v-model="activeIndex" type="card" @tab-click="handleClick">
      <el-tab-pane label="报价中" name="1" style="width: 25%"></el-tab-pane>
      <el-tab-pane label="已报价" name="2" style="width: 25%"></el-tab-pane>
      <el-tab-pane label="已中标" name="3" style="width: 25%"></el-tab-pane>
      <el-tab-pane label="已结束" name="4" style="width: 25%"></el-tab-pane>
    </el-tabs>

    <div class="filter-container">
      <!-- <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleDownload()">导出</el-button> -->
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-d-arrow-left"
        @click="undo()"
        >撤销中标</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-truck"
        @click="batchInspection()"
        >批量送检</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-check"
        @click="qualified()"
        >确认结束（检验合格）</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-close"
        @click="noQualified()"
        >确认结束（检验不合格）</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        @click="secondRelease()"
        >二次发布</el-button
      >
    </div>

    <el-table
      v-loading="listLoading"
      :data="purchaseManage"
      element-loading-text="正在查询中。。。"
      @selection-change="handleSelectionChange"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        type="selection"
        width="50"
        :selectable="selectable"
        align="center"
        fixed="left"
        :resizable="false"
      />
      <el-table-column align="center" label="编号" prop="code" />
      <el-table-column align="center" label="药材名" prop="herbName" />
      <el-table-column align="center" label="规格" prop="specifications" />
      <el-table-column align="center" label="需求数量" prop="needAmount" />
      <el-table-column align="center" label="收货数量" prop="receivedAmount">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.checkStatus == 0"
            v-model="scope.row.receivedAmount"
            :data-price="scope.row.price"
            type="number"
            placeholder="收货数量"
            style="text-align:center"
          >
          </el-input>
          <span v-else>{{ scope.row.receivedAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="单位" prop="measurementUnit" />
      <el-table-column align="center" label="供应商" prop="companyName" />
      <el-table-column align="center" label="供应商电话" prop="supplyContactTel" />
      <el-table-column align="center" label="报价(元)" prop="supplyPrice"/>
      <el-table-column align="center" label="预计到货时间" prop="inspectionCompletionTime" :formatter="formatDate"/>
      <el-table-column align="center" label="送检状态" prop="checkStatus">
        <template slot-scope="scope">
          <el-tag v-if="(new Date(scope.row.inspectionCompletionTime)).getTime()+ 3600 * 1000 * 24<Date.now()&&scope.row.checkStatus==0" :type="'danger'">{{ '超时未到货' }}</el-tag>
          <el-tag v-else :type="scope.row.checkStatus==0 ? '' : 'success'">{{  checkDic[scope.row.checkStatus] }}</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog title="二次发布" :visible.sync="boxVisible">
      <el-form
        ref="secondReleaseForm"
        :rules="rules"
        :model="secondReleaseForm"
        status-icon
        label-position="left"
        label-width="130px"
        style="width: 800px; margin-left: 50px"
      >
        <el-form-item label="采购计划名" prop="remark" style="width: 400px">
          <el-input v-model="secondReleaseForm.name" />
        </el-form-item>
        <el-form-item label="报价截止时间" prop="dueTime" style="width: 400px;">
          <el-date-picker
            v-model="secondReleaseForm.dueTime"
            type="datetime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="23:59:59"
          />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName" style="width: 400px">
          <el-input v-model="secondReleaseForm.contactName" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactTel" style="width: 400px">
          <el-input v-model="secondReleaseForm.contactTel" />
        </el-form-item>
        <el-form-item
          label="收货地址"
          prop="inventoryPlace"
          style="width: 400px"
        >
          <el-select
            v-model="secondReleaseForm.addressId"
            clearable
            style="width: 200px"
            class="filter-item"
            placeholder="收货地址"
          >
            <el-option
              v-for="item in addressList"
              :key="item.id"
              :label="item.addressDetail"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-button v-if="dialogStatus!='view'" :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload(false)">导入模板下载</el-button>
        <a v-if="dialogStatus!='view'" href="javascript:;" class="file" icon="el-icon-download">导入
          <input id="upload" class="a-upload" type="file" @change="importfxx(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
        </a> -->

        <!-- 查询结果 -->
        <el-table
          v-loading="listLoading"
          :data="herbList"
          element-loading-text="正在查询中。。。"
          border
          fit
          highlight-current-row
        >
          <el-table-column align="center" label="编号" prop="code" />

          <el-table-column align="center" label="药材名" prop="herbName" />

          <el-table-column align="center" label="规格" prop="specifications" />

          <el-table-column align="center" label="数量" prop="number">
            <template slot-scope="scope">
              {{ scope.row.needAmount - scope.row.receivedAmount }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="单位" prop="measurementUnit" />

          <el-table-column
            align="center"
            label="操作"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                type="danger"
                size="mini"
                @click="handleHerbListDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="boxVisible = false">取消</el-button>
        <el-button type="primary" @click="createData(0)">保存</el-button>
        <el-button type="primary" @click="createData(1)">保存并发布</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<style>
</style>

<script>
import {
  fetchPurchaseAndItemList,
  undo,
  batchInspection,
  qualified,
  noQualified,
  createPurchase,
} from "@/api/purchaseManage";
import { uploadPath } from "@/api/storage";
import { queryAddress } from "@/api/purchase";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { thumbnail, toPreview } from "@/utils/index";

export default {
  name: "winBidding",
  components: { Pagination },
  data() {
    return {
      thumbnail,
      toPreview,
      id: "",
      uploadPath,
      itemId: "",
      index: "",
      activeIndex: "3",
      purchase: {
        name: undefined,
        dueTime: undefined,
        needHerb: undefined,
        contactName: undefined,
        contactTel: undefined,
        addTime: undefined,
      },
      purchaseManage: [
        {
          receivedAmount: "",
        },
      ],
      levelDic: ["个人", "饮片厂", "经销商"],
      checkDic: ["待送检", "送检中"],
      listLoading: true,
      boxVisible: false,
      has: "primary",
      not: "default",
      shopList: [],
      selectList: [],
      addressList: [],
      type: 0,
      rules: {
        code: [
          { required: true, message: "药材编号不能为空", trigger: "blur" },
          { pattern: /^[a-zA-Z0-9]+$/, message: "只能数字加英文" },
        ],
        herbName: [
          { required: true, message: "药材名称不能为空", trigger: "blur" },
        ],
        specifications: [
          { required: true, message: "规格不能为空", trigger: "blur" },
        ],
        coefficient: [
          { required: true, message: "系数不能为空", trigger: "blur" },
          {
            pattern: /(^(([1-9]([0-9]+)?)|(0{1}))(\.[0-9]{1,2})?$)/,
            message: "系数只能为数字",
          },
        ],
      },
      queryQuery: {
        purchaseId: "",
      },
      secondReleaseForm: {
        name: undefined,
        dueTime: undefined,
        needHerb: undefined,
        contactName: undefined,
        contactTel: undefined,
        addTime: undefined,
      },
      herbList: "",
      listQuery: {
        page: 1,
        limit: 20,
        type: 2,
        remark: "",
        status: "2",
        id: undefined,
        name: undefined,
        sort: "add_time",
        order: "desc",
      },
      statusDic: {
        2: "已发布",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.id = this.$route.query.id;
      this.listQuery.id = this.$route.query.id;
      this.listLoading = true;
      fetchPurchaseAndItemList(this.listQuery)
        .then((response) => {
          this.purchase = response.data.data.purchase;
          this.purchaseManage = response.data.data.purchaseManage;
          this.purchaseManage.forEach((element) => {
            if (element.receivedAmount == undefined) {
              this.$set(element, "receivedAmount", element.needAmount);
            }
          });
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.listLoading = false;
        });
    },
    formatDate(row, column) {
      // 获取单元格数据
      let data = row[column.property]
      if(data == null) {
        return null
      }
      let dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
    },
    handleClick(tab, event) {
      if (tab.name == 1) {
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push({
          path: "/mall/noQuotation",
          query: { id: this.id },
        });
      } else if (tab.name == 2) {
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push({
          path: "/mall/hasQuotation",
          query: { id: this.id },
        });
      } else if (tab.name == 3) {
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push({ path: "/mall/winBidding", query: { id: this.id } });
      } else if (tab.name == 4) {
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.push({ path: "/mall/finish", query: { id: this.id } });
      }
    },
    selectable(row) {
      if (row.bytstatus === 4) {
        return false;
      } else {
        return true;
      }
    },
    handleHerbListDelete(row) {
      this.herbList.splice(
        this.herbList.findIndex((arr) => arr.code == row.code),
        1
      );
    },
    secondRelease() {
      if (this.selectList.length != 0) {
        if (this.selectList.findIndex((arr) => arr.checkStatus == 0) == -1) {
          if (
            this.selectList.findIndex(
              (arr) => arr.receivedAmount == arr.needAmount
            ) == -1
          ) {
            this.$set(this.secondReleaseForm, "id", this.purchase.id);
            this.$set(this.secondReleaseForm, "name", this.purchase.name);
            this.$set(this.secondReleaseForm, "dueTime", this.purchase.dueTime);
            this.$set(this.secondReleaseForm,"needHerb",this.purchase.needHerb);
            this.$set(this.secondReleaseForm,"contactName",this.purchase.contactName);
            this.$set(this.secondReleaseForm,"contactTel",this.purchase.contactTel);
            this.$set(this.secondReleaseForm,"addressId",this.purchase.addressId);
            this.herbList = this.selectList;
            this.boxVisible = true;
            queryAddress()
              .then((response) => {
                this.addressList = response.data.data;
              })
              .catch((response) => {
                this.$notify.error({
                  title: "地址查询失败",
                  message: response.data.errmsg,
                });
              });
            this.$nextTick(() => {
              this.$refs["secondReleaseForm"].clearValidate();
            });
          } else {
            this.$message({
              message: "需求数量和收货数量相同，无法二次发布，请重新选择",
              type: "warning",
            });
          }
        } else {
          this.$message({
            message: "待送检状态，无法二次发布，请重新选择",
            type: "warning",
          });
        }
      } else {
        this.$message({
          message: "请至少选择一个",
          type: "warning",
        });
      }
    },
    createData(status) {
      var that = this;
      this.$refs["secondReleaseForm"].validate((valid) => {
        if (valid) {
          this.secondReleaseForm.status = status;
          let data = {};
          data.dataForm = this.secondReleaseForm;
          data.herbList = this.herbList;
          data.dataForm.inventoryplace = that.addressList.find(
            (arr) => arr.id == data.dataForm.addressId
          ).addressDetail;
          if (data.herbList.length != 0) {
            this.$confirm("此操作将创建新报价,是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                createPurchase(data)
                  .then((response) => {
                    this.getList();
                    this.boxVisible = false;
                    this.$notify.success({
                      title: "成功",
                      message: "创建成功",
                    });
                  })
                  .catch((response) => {
                    this.$notify.error({
                      title: "失败",
                      message: response.data.errmsg,
                    });
                  });
              })
              .catch(() => {
                this.stepLoading = false;
                this.$message({
                  type: "info",
                  message: "已取消",
                });
              });
          } else {
            this.$message.error("采购药材不能为空");
          }
        }
      });
    },
    ellipsis (value) {
      if (!value) return ''
      if (value.length > 20) {
        return value.slice(0,20) + '...'
      }
      return value
    },
    undo() {
      if (this.selectList.length != 0) {
        if (this.selectList.findIndex((arr) => arr.checkStatus != 0) == -1) {
          this.$confirm("此操作将撤销中标,是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
          undo(this.selectList)
            .then((response) => {
              this.$notify.success({
                title: "成功",
              });
              this.getList();
            })
            .catch(() => {
              this.$notify.error({
                title: "失败",
              });
              this.downloadLoading = false;
            });
            })
              .catch(() => {
                this.stepLoading = false;
                this.$message({
                  type: "info",
                  message: "已取消",
                });
              });
        } else {
          this.$message({
            message: "除待送检状态，其他无法撤销，请重新选择",
            type: "warning",
          });
        }
      } else {
        this.$message({
          message: "请至少选择一个",
          type: "warning",
        });
      }
    },
    batchInspection() {
      if (this.selectList.length != 0) {
        if (this.selectList.findIndex((arr) => arr.checkStatus != 0) == -1) {
          if (
            !this.selectList.findIndex(
              (arr) =>
                arr.receivedAmount <= arr.needAmount &&
                arr.receivedAmount != "" &&
                arr.receivedAmount != 0
            )
          ) {
            this.$confirm("此操作将无法撤销,是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
            batchInspection(this.selectList)
              .then((response) => {
                this.$notify.success({
                  title: "成功",
                });
                this.getList();
              })
              .catch(() => {
                this.$notify.error({
                  title: "失败",
                });
                this.downloadLoading = false;
              });
              })
              .catch(() => {
                this.stepLoading = false;
                this.$message({
                  type: "info",
                  message: "已取消",
                });
              });
          } else {
            this.$message({
              message: "请检查收货数量是否正确,且不能为空",
              type: "warning",
            });
          }
        } else {
          this.$message({
            message: "除待送检状态，其他无法送检，请重新选择",
            type: "warning",
          });
        }
      } else {
        this.$message({
          message: "请至少选择一个",
          type: "warning",
        });
      }
    },
    qualified() {
      if (this.selectList.length != 0) {
        if (this.selectList.findIndex((arr) => arr.checkStatus != 1) == -1) {
          this.$confirm("此操作将无法撤销,是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
          qualified(this.selectList)
            .then((response) => {
              this.$notify.success({
                title: "成功",
              });
              this.getList();
            })
            .catch(() => {
              this.$notify.error({
                title: "结束失败",
              });
              this.downloadLoading = false;
            });
            })
              .catch(() => {
                this.stepLoading = false;
                this.$message({
                  type: "info",
                  message: "已取消",
                });
              });
        } else {
          this.$message({
            message: "除送检中状态，其他无法收货，请重新选择",
            type: "warning",
          });
        }
      } else {
        this.$message({
          message: "请至少选择一个",
          type: "warning",
        });
      }
    },
    noQualified() {
      if (this.selectList.length != 0) {
        if (this.selectList.findIndex((arr) => arr.checkStatus != 1) == -1) {
          this.$confirm("此操作将无法撤销,是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
          noQualified(this.selectList)
            .then((response) => {
              this.$notify.success({
                title: "成功",
              });
              this.getList();
            })
            .catch(() => {
              this.$notify.error({
                title: "结束失败",
              });
              this.downloadLoading = false;
            });
            })
              .catch(() => {
                this.stepLoading = false;
                this.$message({
                  type: "info",
                  message: "已取消",
                });
              });
        } else {
          this.$message({
            message: "除送检中状态，其他无法退货，请重新选择",
            type: "warning",
          });
        }
      } else {
        this.$message({
          message: "请至少选择一个",
          type: "warning",
        });
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectList = selection;
    },
    // 导出的方法
    handleDownload() {
      this.downloadLoading = true;
      this.listQuery.selectAll = true;
      fetchPurchaseAndItemList(this.listQuery)
        .then((response) => {
          require.ensure([], () => {
            const {
              export_json_to_excel,
            } = require("../../vendor/Export2Excel"); // 注意这个Export2Excel路径
            const tHeader = [
              "药材编号",
              "药材名称",
              "规格",
              "单位",
              "需求数量",
              "已报价供应商数",
              "未报价供应商数",
            ]; // 上面设置Excel的表格第一行的标题
            const filterVal = [
              "code",
              "herbName",
              "specifications",
              "measurementUnit",
              "needAmount",
              "yet",
              "sum",
            ]; // 上面的index、nickName、name是tableData里对象的属性key值
            const list = response.data.data.list; // 把要导出的数据tableData存到list
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(
              tHeader,
              data,
              flag ? "药材品类信息" : "药材品类导入模板"
            ); // 最后一个是表名字
          });
          this.downloadLoading = false;
        })
        .catch(() => {
          this.$notify.error({
            title: "导出失败",
          });
          this.downloadLoading = false;
        });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script>
